package cn.e4j.modular.api;

import cn.digiwin.wx.qyh.common.WeixinComm;
import cn.digiwin.wx.utils.HttpUtil;
import cn.e4j.config.properties.E4jProperties;
import cn.e4j.core.base.controller.BaseController;
import cn.e4j.core.cache.CacheKey;
import cn.e4j.core.cache.CacheUtil;
import cn.e4j.core.common.exception.BizExceptionEnum;
import cn.e4j.core.dto.impl.Dto;
import cn.e4j.core.dto.requestDtoResolver.DtoParam;
import cn.e4j.core.dto.requestDtoResolver.DtoWapper;
import cn.e4j.core.reqres.response.ErrorResponseData;
import cn.e4j.core.reqres.response.ResponseData;
import cn.e4j.core.reqres.response.SuccessResponseData;
import cn.e4j.core.util.BASE64DecodedMultipartFile;
import cn.e4j.core.util.FileUtil;
import cn.e4j.core.util.ToolUtil;
import cn.e4j.modular.system.entity.SysOrg;
import cn.e4j.modular.system.mapper.SysOrgMapper;
import cn.e4j.modular.system.service.SysRoleService;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import sun.misc.BASE64Decoder;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 接口控制器提供
 *
 * @author wenchuan.li
 * @Date 2018/7/20 23:39
 */
@Controller
@RequestMapping("/api/sys/")
@Slf4j
public class SystemController extends BaseController {

    @Autowired
    private SysOrgMapper sysOrgMapper;

    @Autowired
    private SysRoleService sysRoleService;

    @Autowired
    private E4jProperties e4jProperties;

    /**
     * 记录js报错日志
     */
    @RequestMapping(value = "saveJsError", method = RequestMethod.POST)
    @ResponseBody
    public ResponseData saveJsError(@DtoParam DtoWapper wapper) {
        Dto dto = wapper.getDto();
        log .error("JS erorMsg--***:{}--{}", dto.getString("user"), dto.getString("errorMsg"));
        return SUCCESS_TIP;
    }

    /**
     * 上传图片
     */
    @RequestMapping(method = RequestMethod.POST, path = "uploadBase64")
    @ResponseBody
    public ResponseData uploadBase64(@DtoParam DtoWapper wapper) {
        List<Map<String, String>> paths;
        String basePath = null;


        BASE64Decoder decoder = new BASE64Decoder();
        Dto dto = wapper.getDto();
        try {
            String imgStr = (String) dto.get("imgStr");
            if (ToolUtil.isEmpty(imgStr)) {
                return new ErrorResponseData(BizExceptionEnum.UPLOAD_ERROR.getMessage());
            }
            Map<String, String> imgmap = new HashMap<String, String>();

            String rootPath = ToolUtil.getWebRootPath(null);
            rootPath = rootPath.substring(0, rootPath.lastIndexOf("/"));
            basePath = rootPath + File.separator + this.e4jProperties.getFileUploadPath();


            List<MultipartFile> files = new ArrayList<>();

            files.add(BASE64DecodedMultipartFile.base64ToMultipart(imgStr));

            String tableName = dto.getString("tableName");

            if (tableName != null && !tableName.equals("")) {
                basePath += (tableName + "/");
            }

            paths = FileUtil.saveFiles(files, basePath);
        } catch (IOException e) {
            e.printStackTrace();
            return new ErrorResponseData(BizExceptionEnum.UPLOAD_ERROR.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
            return new ErrorResponseData(BizExceptionEnum.UPLOAD_ERROR.getMessage());
        }

        return new SuccessResponseData(paths.get(0));
    }
	
	 /**
     * 从微信服务器下载图片
     */
    @RequestMapping(method = RequestMethod.POST, path = "uploadByWxServerIds")
    @ResponseBody
    public ResponseData uploadByWxServerIds(@DtoParam DtoWapper wapper) {
        //List<Map<String, String>> paths;
        String basePath = null;
        Dto dto = wapper.getDto();
        List<Map<String, String>> returnPaths = new ArrayList();

        try {
            JSONObject request = dto.getReqJsonObject();
            JSONArray ids = request.getJSONArray("ids");
            if (ToolUtil.isEmpty(ids)) {
                return new ErrorResponseData(BizExceptionEnum.UPLOAD_ERROR.getMessage());
            }

            String rootPath = ToolUtil.getWebRootPath(null);
            rootPath = rootPath.substring(0, rootPath.lastIndexOf("/"));
            basePath = this.e4jProperties.getFileUploadPath();


            // List<MultipartFile> files = new ArrayList<>();

            String tableName = request.getString("tableName");

            if (tableName != null && !tableName.equals("")) {
                basePath += tableName;
            }

            basePath += ("/");

            FileUtil.createFolder(rootPath + File.separator + basePath, false);

            for (int i = 0; i < ids.size(); i++) {
                //URL url = new URL(urlHttp);
                //BufferedImage img = ImageIO.read(url);
                //ImageIO.write(img, "jpg", new File(basePath + System.currentTimeMillis() + ".jpg"));
                Map<String, String> map = new HashMap();
                map.put("name", System.currentTimeMillis() + ".jpg");
                map.put("path", basePath);
                String imgPath = map.get("path") + map.get("name");
                String imgFullPath = rootPath + File.separator + imgPath;

                // 2019-11-27
//                final WxCpService wxCpService = WxUtils.getCpService(getHttpServletRequest());
//                File file = wxCpService.getMediaService().download(ids.getString(i));
//                InputStream in = new FileInputStream(file);
//
//                FileUtil.createFolder(imgFullPath, true);
//                FileUtil.writeFile(imgFullPath, in);
                //旧的方式
                HttpUtil.saveRemoteFile(WeixinComm.getWxMediaURL(ids.getString(i)), imgFullPath);
                returnPaths.add(map);
            }

            //paths = FileUtil.saveFiles(files, basePath);
        } catch (IOException e) {
            e.printStackTrace();
            return new ErrorResponseData(BizExceptionEnum.UPLOAD_ERROR.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
            return new ErrorResponseData(BizExceptionEnum.UPLOAD_ERROR.getMessage());
        }

        return new SuccessResponseData(returnPaths);
    }

    /**
     * 查询部门列表
     */
    @RequestMapping(method = RequestMethod.POST, path = "getOrgs")
    @ResponseBody
    public ResponseData getOrgs() {
        List<SysOrg> sysOrgs = sysOrgMapper.getOrgs(null);
        return ResponseData.success(sysOrgs);
    }

    /**
     * 查询角色列表
     */
    @RequestMapping("/getRolesList")
    @ResponseBody
    public ResponseData getRolesList(@DtoParam DtoWapper dtoWapper) {
        Dto inDto = dtoWapper.getDto();
        inDto.put("IS_ENABLE", "1");
        return ResponseData.success(sysRoleService.getRolesList(null, inDto));
    }

}

